package com.jiuwu.spring.eshop.controller;

import com.jiuwu.spring.eshop.db.entity.Goods;
import com.jiuwu.spring.eshop.db.entity.OrderEt;
import com.jiuwu.spring.eshop.respository.GoodsRepository;
import com.jiuwu.spring.eshop.respository.OrderRepository;
import com.jiuwu.spring.eshop.respository.VGoodsRepository;
import com.jiuwu.spring.eshop.respository.VTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Optional;

@Controller
public class GoodsDetailsController {



    @Autowired
    GoodsRepository goodsRepository;

    @Autowired
    VTypeRepository vTypeRepository;

    @Autowired
    VGoodsRepository vGoodsRepository;

    @RequestMapping("/goodDetails")
    public String goodDetails(@RequestParam(name = "goodsId")Integer goodsId,
                              Model model){
        Optional<Goods> goods = goodsRepository.findById(goodsId);

        goods.ifPresent(good -> {
            good.setGoodsHit(1+good.getGoodsHit());
            goodsRepository.save(good);
            model.addAttribute("good",good);
        });
        model.addAttribute("newGoods",
                goodsRepository.findTop4ByIsNewEqualsOrderByGoodsCreatedTimeDesc(1));
        return "/goods_details";

    }

    @RequestMapping("/goodsType")
    public String goodsType(@RequestParam("type") Integer type,Model model){

        vTypeRepository.findById(type).ifPresent(vtype->{
            model.addAttribute("vType",vtype);
            model.addAttribute("allGoods",vGoodsRepository.findAllBySubIdEquals(type));
        });

        return "/goods_type_deal";
    }

}
